<template>
  <div class="min-h-screen bg-gray-100 pb-20">
    <!-- Header -->
    <header
        class="fixed top-0 left-0 w-full h-14 bg-blue-600 flex items-center z-50 px-4 shadow-md"
        @click="getLocation"
    >
      <!-- 定位图标 -->
      <div class="w-5 h-5 mr-2 text-white">
        <i class="i-mdi-map-marker"></i>
      </div>
      <!-- 当前位置文本 -->
      <p v-if="!isGettingLocation" class="text-white font-medium truncate">
        {{ currentLocation }}
      </p>
      <p v-else class="text-white font-medium truncate">
        正在定位中...
      </p>
      <!-- 下拉箭头 -->
      <i class="i-mdi-chevron-down ml-1 text-white"></i>
    </header>

    <!-- Search Box -->
    <div class="h-14"></div>
    <div
        :class="{ 'fixed top-14 left-0 right-0 z-40 bg-white shadow-sm': isFixed }"
        class="transition-all duration-300 px-4 py-2"
        ref="searchBox"
    >
      <div class="relative">
        <input
            type="text"
            placeholder="搜索饿了么商家、商品名称"
            class="w-full h-10 pl-4 pr-10 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-400"
        />
        <i class="i-mdi-magnify absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
      </div>
    </div>

    <!-- Food Types -->
    <ul class="grid grid-cols-5 gap-4 p-4 bg-white">
      <li
          v-for="(item, index) in foodTypes"
          :key="index"
          @click="handleCategoryClick(item)"
          class="flex flex-col items-center justify-center space-y-1 text-center"
      >
        <img :src="item.image" :alt="item.name" class="w-10 h-10 object-contain">
        <p class="text-sm text-gray-700">{{ item.name }}</p>
      </li>
    </ul>

    <!-- Banner -->
    <div class="relative h-40 mt-2 overflow-hidden bg-cover bg-center" style="background-image: url(/img/index_banner.png)">
      <div class="absolute inset-0 bg-black bg-opacity-30 flex flex-col justify-center p-6 text-white">
        <h3 class="text-xl font-bold">品质套餐</h3>
        <p class="text-sm mb-3">搭配齐全吃得好</p>
        <router-link to="/flashsale" class="inline-block text-sm text-amber-200 font-semibold">立即抢购 &gt;</router-link>
      </div>
    </div>

    <!-- Super Member Card -->
    <div class="mx-4 my-4 p-4 bg-amber-100 rounded-lg flex items-center justify-between text-amber-800">
      <div class="flex items-center">
        <img src="/img/super_member.png" alt="超级会员" class="w-6 h-6 mr-2">
        <h3 class="font-medium">超级会员</h3>
        <p class="text-xs ml-2">&#8226; 每月享超值权益</p>
      </div>
      <div class="text-xs font-medium cursor-pointer">立即开通 &gt;</div>
    </div>

    <!-- 推荐商家标题 -->
    <div class="flex justify-center items-center my-4">
      <div class="w-6 h-px bg-gray-300"></div>
      <p class="text-sm mx-4 text-gray-600">推荐商家</p>
      <div class="w-6 h-px bg-gray-300"></div>
    </div>

    <!-- Sort Filters -->
    <div class="flex justify-around text-sm text-gray-600 bg-white py-2 px-4">
      <span>综合排序<i class="i-mdi-chevron-down ml-1"></i></span>
      <span>距离最近</span>
      <span>销量最高</span>
      <span>筛选<i class="i-mdi-filter ml-1"></i></span>
    </div>

    <!-- 商家列表 -->
    <ul class="mt-2 space-y-4 px-4">
      <li
          v-for="(shop, index) in shops"
          :key="index"
          @click="goToBusinessInfo(shop.id)"
          class="bg-white rounded-lg shadow-sm overflow-hidden flex items-start p-4"
      >
        <!-- Logo -->
        <img :src="shop.logo" :alt="shop.name" class="w-16 h-16 object-cover rounded-md">

        <!-- Info -->
        <div class="ml-4 flex-1">
          <div class="flex justify-between items-start">
            <h3 class="text-base font-semibold">{{ shop.name }}</h3>
            <div class="w-5 h-5 bg-red-500 text-white flex justify-center items-center rounded-full text-xs">
              新
            </div>
          </div>

          <!-- 星级评分 -->
          <div class="flex items-center mt-1">
            <i v-for="n in 5" :key="n" class="i-mdi-star text-yellow-400"></i>
            <p class="text-xs text-gray-500 ml-1">评分 {{ shop.rating }} 月售{{ shop.sales }}单</p>
          </div>

          <!-- 配送信息 -->
          <p class="text-xs text-gray-500 mt-1">
            ￥{{ shop.minOrder }}起送 | ￥{{ shop.deliveryFee }}配送
          </p>
          <p class="text-xs text-gray-500">
            {{ shop.distance }}km | {{ shop.time }}分钟
          </p>

          <!-- 描述标签 -->
          <div class="mt-1 inline-block bg-green-100 text-green-700 text-xs px-2 py-0.5 rounded">
            {{ shop.description }}
          </div>

          <!-- 活动 -->
          <div class="flex justify-between items-center mt-2">
            <div class="flex items-center">
              <div class="w-4 h-4 bg-green-600 text-white text-xs flex justify-center items-center rounded">新</div>
              <p class="text-xs text-gray-600 ml-1">首单立减9元</p>
            </div>
            <div class="flex items-center text-xs text-gray-400">
              <span>2个活动</span>
              <i class="i-mdi-chevron-down ml-1"></i>
            </div>
          </div>
        </div>
      </li>
    </ul>

    <!-- Footer Menu -->
    <FooterMenu />
  </div>
</template>

<script setup lang="ts">

import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import FooterMenu from "../../components/common/FooterMenu.vue"

const router = useRouter()
const isFixed = ref(false)
const searchBox = ref(null)

// 当前显示的位置信息
const currentLocation = ref<string>('云南大学呈贡校区南门')
// 是否正在获取位置
const isGettingLocation = ref<boolean>(false)
// 食物分类

const foodTypes = [
  { name: '美食', image: '/img/dcfl01.png' },
  { name: '早餐', image: '/img/dcfl02.png' },
  { name: '跑腿代购', image: '/img/dcfl03.png' },
  { name: '汉堡披萨', image: '/img/dcfl04.png' },
  { name: '甜品饮品', image: '/img/dcfl05.png' },
  { name: '速食简餐', image: '/img/dcfl06.png' },
  { name: '地方小吃', image: '/img/dcfl07.png' },
  { name: '米粉面馆', image: '/img/dcfl08.png' },
  { name: '包子粥铺', image: '/img/dcfl09.png' },
  { name: '炸鸡炸串', image: '/img/dcfl10.png' }
]

// 商家数据
const shops = [
  {
    id:1,
    name: '万家饺子（软件园E18店）',
    logo: '/img/sj01.png',
    rating: '4.9',
    sales: '345',
    minOrder: 15,
    deliveryFee: 3,
    distance: '3.22',
    time: '30',
    description: '各种饺子'
  },
  {
    id:2,
    name: '小锅饭豆腐馆（全运店）',
    logo: '/img/sj02.png',
    rating: '4.9',
    sales: '345',
    minOrder: 15,
    deliveryFee: 3,
    distance: '3.22',
    time: '30',
    description: '东北特色菜'
  },
  {
    id:3,
    name: '麦当劳麦乐送（全运路店）',
    logo: '/img/sj03.png',
    rating: '4.9',
    sales: '345',
    minOrder: 15,
    deliveryFee: 3,
    distance: '3.22',
    time: '30',
    description: '汉堡薯条'
  },
  {
    id:4,
    name: '米村拌饭（浑南店）',
    logo: '/img/sj04.png',
    rating: '4.9',
    sales: '345',
    minOrder: 15,
    deliveryFee: 3,
    distance: '3.22',
    time: '30',
    description: '米饭快餐'
  },
  {
    id:5,
    name: '申记串道（中海康城店）',
    logo: '/img/sj05.png',
    rating: '4.9',
    sales: '345',
    minOrder: 15,
    deliveryFee: 3,
    distance: '3.22',
    time: '30',
    description: '烧烤炸串'
  }
]

function goToBusinessInfo(shopId) {
  router.push(`/shop/${shopId}`)
}

/**
 * 获取用户当前位置（经纬度）
 */
function getLocation(): void {
  if (!navigator.geolocation) {
    alert('您的浏览器不支持地理位置服务')
    return
  }

  isGettingLocation.value = true

  navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords
        console.log('获取到的经纬度:', { latitude, longitude })

        // 模拟显示经纬度，实际项目可替换为逆地理编码结果（如高德地图API）
        currentLocation.value = `纬度: ${latitude.toFixed(4)}, 经度: ${longitude.toFixed(4)}`
        isGettingLocation.value = false
      },
      (error) => {
        isGettingLocation.value = false
        switch (error.code) {
          case error.PERMISSION_DENIED:
            alert('用户拒绝了地理位置请求，请手动输入位置')
            break
          case error.POSITION_UNAVAILABLE:
            alert('无法获取当前位置，请稍后再试')
            break
          case error.TIMEOUT:
            alert('获取位置超时，请检查网络')
            break
          default:
            alert('未知错误，请重试')
            break
        }
      },
      {
        enableHighAccuracy: true, // 高精度模式
        timeout: 5000,             // 超时时间
        maximumAge: 0              // 不使用缓存位置
      }
  )
}
function handleCategoryClick(category) {
  if (category.name === '美食') {
    router.push('/category/food')
  } else {
    // 其他分类跳转逻辑（比如通用分类页）
    router.push('/category/default')
  }
}

// 监听滚动事件实现吸顶效果
onMounted(() => {
  window.addEventListener('scroll', () => {
    const scrollTop = window.scrollY || document.documentElement.scrollTop
    isFixed.value = scrollTop >= 50
  })
})
</script>